package com.example.musiccommunity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.musiccommunity.ManagerPage.ManagerHome;
import com.example.musiccommunity.UserPage.UserHome;
import com.example.musiccommunity.bean.Song;
import com.example.musiccommunity.bean.User;
import com.example.musiccommunity.util.ImageUtil;
import com.example.musiccommunity.util.MusicDataLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

//    public static String ip="http://47.93.14.182:8080";
    public static String ip="http://171.12.4.175:22960/music-api";

    public static RequestQueue requestQueue;//请求队列声明
    private TextView loginTitle;
    private EditText loginUsername;
    private EditText loginPassword;
    private RadioButton loginManage;
    private RadioButton login_user;
    private Button loginButtonLogin,register;
    public static User user=new User();
    public static  ArrayList<Song>  songs=new ArrayList<>();
    public static ArrayList<String> styleArray=new ArrayList<>();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestQueue= Volley.newRequestQueue(this);
        loginTitle = findViewById(R.id.login_title);
        loginUsername = findViewById(R.id.login_username);
        loginPassword = findViewById(R.id.login_password);
        loginManage = findViewById(R.id.login_manage);
        login_user = findViewById(R.id.login_user);
        loginButtonLogin = findViewById(R.id.login_button_login);
        register = findViewById(R.id.register);

        loginButtonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqString();
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this ,RegisterActivity.class);
                startActivity(intent);
            }
        });
        init();

//        if (ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION )
//                != PackageManager.PERMISSION_GRANTED) {
//            //向系统申请权限
//            ActivityCompat.requestPermissions( this,
//                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1 );
//        }
//        if (ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION )
//                != PackageManager.PERMISSION_GRANTED) {
//            //向系统申请权限
//            ActivityCompat.requestPermissions( this,
//                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1 );
//        }
//        if (ContextCompat.checkSelfPermission( this, Manifest.permission.INTERNET )
//                != PackageManager.PERMISSION_GRANTED) {
//            //向系统申请权限
//            ActivityCompat.requestPermissions( this,
//                    new String[]{Manifest.permission.INTERNET}, 1 );
//        }
//        if (ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE )
//                != PackageManager.PERMISSION_GRANTED) {
//            //向系统申请权限
//            ActivityCompat.requestPermissions( this,
//                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1 );
//        }
        readRequest();
    }

    void reqString(){//判断登录
        String s="用户";
        if(!login_user.isChecked()){
            s="管理员";
        }
        String n=loginUsername.getText().toString();
        String p=loginPassword.getText().toString();
        String url=ip+"/user/login?name="+n+"&psw="+p+"&type="+s;
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d("user***********user",s.toString());
                if(s==null || s.equals("")){
                    Toast.makeText(MainActivity.this, "登录失败，账号或密码错误", Toast.LENGTH_SHORT).show();
                }else{
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(s);
                        String name = jsonObject.get("name").toString();
                        String psw=jsonObject.get("password").toString();
                        String email=jsonObject.get("email").toString();
                        String img=jsonObject.get("img").toString();
                        Bitmap bit = ImageUtil.base64ToBitmap(img);
                        String type=jsonObject.get("type").toString();
                        user=new User(name,psw,email,new BitmapDrawable(bit),type);

                        Intent intent = new Intent();
                        if(login_user.isChecked())
                            intent.setClass(MainActivity.this , UserHome.class);
                        else
                            intent.setClass(MainActivity.this , ManagerHome.class);
                        startActivity(intent);
                    } catch (JSONException e) {
                        System.out.println(e.toString());
                        throw new RuntimeException(e);
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                Toast.makeText(getBaseContext(), "登录失败，用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        requestQueue.add(stringRequest);

    }
    void init(){
        // 加载歌曲数据
        songs = (ArrayList<Song>) MusicDataLoader.loadSongs(this);
        if (songs == null || songs.isEmpty()) {
            Toast.makeText(this, "没有找到歌曲数据", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Integer> venueCountMap = new HashMap<>();
        for (Song s : songs) {
            venueCountMap.put(s.getStyle(), venueCountMap.getOrDefault(s.getStyle(), 0) + 1);
        }

        styleArray=new ArrayList<>();
        for (Map.Entry<String, Integer> entry : venueCountMap.entrySet()) {
            System.out.println("Venue: " + entry.getKey() + ", Count: " + entry.getValue());
            styleArray.add(entry.getKey());
        }

        styleArray.add("音乐推荐");
        Collections.reverse(styleArray);
        // 遍历歌曲列表并获取资源ID
//        for (Song song : songs) {
//            int audioResId = MusicDataLoader.getRawResourceId(this, song.getRawResId());
//            int coverResId = MusicDataLoader.getDrawableResourceId(this, song.getCoverResId());
//
//            String info = String.format("歌曲: %s, 专辑: %s, 演唱者: %s, 音频ID: %d, 封面ID: %d",
//                    song.getName(),
//                    song.getAlbum(),
//                    song.getArtist(),
//                    audioResId,
//                    coverResId);
//            System.out.println(info);
//        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    void readRequest() {             //获取权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET}, 1);
            }
        }
    }
}